import { useState, useEffect, useContext } from 'react';
import { NavBar, List, Button, Popup, Toast } from 'antd-mobile';
import { CopyOutlined } from '@ant-design/icons';
import { useHistory, useRouteMatch } from 'react-router-dom';
import copy from 'copy-text-to-clipboard';

import { ContentType } from '../../../constants';
import Collection from '../../../components/Collection';
// import RtcInvite from '../../Chat/RtcInvite';
import Rtc from '../../Chat/Rtc';
import AvatarImage from '../../../components/AvatarImage';
import { MySdkStoreContext } from '../../../context';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const { params: { userId } } = useRouteMatch();
  const [userInfo, setUserInfo] = useState({});
  const [collectionCompProps, setCollectCompProps] = useState({ visible: false });
  const [rtcPageProps, setRtcPageProps] = useState({ visible: false, isVedioEnable: true });

  useEffect(async () => {
    const info = await mySdkStore.sdk.queryUserInfoById({ queryUserId: userId })
    if (!info) {
      Toast.show('用户不存在');
      return;
    }
    if (info?.userExtraPropertyVO && Object.keys(info.userExtraPropertyVO).length) {
      const allTags = await mySdkStore.sdk.queryFavoriteTags();
      const userTags = allTags.filter(item => info.userExtraPropertyVO[item.code] === 'true').map(item => item.name);
      setUserInfo({ ...info, goodFriendTag: userTags.join(',') });
    } else {
      setUserInfo(info);
    }
  }, []);

  const addConcern = async () => {
    await mySdkStore.sdk.addUserConcern({ relUserId: userId, userId: mySdkStore.mockConfig.userId })
    Toast.show('添加关注成功');
    setUserInfo({ ...userInfo, isConcern: true });
  }

  const removeConcern = async () => {
    await mySdkStore.sdk.removeUserConcern({ relUserId: userId, userId: mySdkStore.mockConfig.userId })
    Toast.show('已取消关注');
    setUserInfo({ ...userInfo, isConcern: false });
  }

  const handleCreateConversation = () => {
    mySdkStore.sdk.createConversation({ type: 'single', subUserId: userId }).then((data) => {
      history.push({ pathname: `/chatDetail/${data.cid}` });
    }, () => {
      Toast.show({
        icon: 'fail',
        content: '操作失败'
      })
    });
  }

  const onParticipantJoinRtcRoom = (res) => {
    const { joinUserId } = res;
    Toast.show(`${joinUserId}已接通`);
    setRtcPageProps({
      visible: true,
      rtcAction: 'continue',
      onClose: () => setRtcPageProps({ visible: false })
    });
  }

  const onParticipantLeaveRtcRoom = (res) => {
    const { leaveUserId } = res;
    Toast.show(`${leaveUserId}已挂断`);
    setRtcPageProps({ visible: false });
  }

  const onParticipantRejectRtcInvite = (res) => {
    const { userId } = res;
    Toast.show(`${userId}已拒绝`);

    const msgBody = {
      msgType: ContentType.Rtc,
      msgContent: { rtcAction: 'hangUp' }
    };
    const msgParams = mySdkStore.sdk.messageBuilder(msgBody);
    mySdkStore.sdk.sendMessage(msgParams).then(res => {
      setRtcPageProps({ visible: false });
    }).catch(e => {
      Toast.show(e.errorMessage || e.message);
    });
  }

  const handleRtc = () => {
    mySdkStore.sdk.createConversation({ type: 'single', subUserId: userId }).then(async (data) => {
      try {
        setRtcPageProps({
          ...rtcPageProps,
          visible: true,
          avatarUrl: userInfo.avatarUrl,
          nickName: userInfo.nickName,
          userName: userInfo.userName,
          userId: userInfo.userId,
          rtcAction: 'invite',
          onClose: () => setRtcPageProps({ visible: false }),
          onVedioEnable: (enable) => setRtcPageProps({ ...rtcPageProps, isVedioEnable: enable }),
        });
        await mySdkStore.sdk.setCurrentCid(data?.cid);
        const params = {
          msgType: ContentType.Rtc,
          msgContent: { 
            rtcAction: 'invite', 
            rtcSlot: {
              publishVideoElementId: 'implusPublishVideoElementId',
              subscribeVideoElementId: 'implusSubscribeVideoElementId',
              subscribeAudioElementId: 'implusSubscribeAudioElementId'
            }
          }
        }
        const msgParams = mySdkStore.sdk.messageBuilder(params);
        const sendResData = await mySdkStore.sdk.sendMessage(msgParams);
      } catch (e) {
        Toast.show('操作失败');
      }
    }, () => {
      Toast.show({
        icon: 'fail',
        content: '操作失败'
      })
    });
  }

  const copyUserId = (e) => {
    copy(userId);
    Toast.show('复制成功');
    e.stopPropagation();
  }

  const handleCollectionOk = async (tagCodes, allTagInfos) => {
    try {
      const tagString = allTagInfos.map(item => item.name).join(',');
      await mySdkStore.sdk.collectUser({ targetUserId: userId, tagCodes });
      await mySdkStore.sdk.updateGoodFriendRelationInfo({ invitedUserId: userId, updateType: 'TAG', tag: tagString });
      setUserInfo({ ...userInfo, goodFriendTag: userInfo.goodFriendTag ? `${userInfo.goodFriendTag},${tagString}` : tagString });
      Toast.show('设置成功');
      setCollectCompProps({ visible: false });
    } catch(e) {
      Toast.show('操作失败');
      console.log(e);
    }
  }

  const handleCollect = () => {
    setCollectCompProps({
      visible: true,
      onOk: handleCollectionOk
    });
  }

  useEffect(() => {
    mySdkStore.sdk.onParticipantJoinRtcRoom = onParticipantJoinRtcRoom;
    mySdkStore.sdk.onParticipantLeaveRtcRoom = onParticipantLeaveRtcRoom;
    mySdkStore.sdk.onParticipantRejectRtcInvite = onParticipantRejectRtcInvite;
  }, []);

  return (<div className="userInfoPage">
    <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>{ userInfo.userName }</NavBar>
    <List style={{ '--border-top': 0, '--border-bottom': 0 }}>
      <List.Item
        prefix={<AvatarImage
          nickName={userInfo.nickName}
          userName={userInfo.userName}
          userId={userId}
          style={{ borderRadius: '12px' }}
          src={userInfo.avatarUrl}
          width={60}
          height={60}
          fit='fill' />}
        description={<div className="userId">ID: { userId } <CopyOutlined style={{ color: '#1890FF' }} onClick={copyUserId} /></div>}
        extra={ userInfo.isConcern ? <Button size="mini" onClick={removeConcern}>取消关注</Button> : <Button size="mini" color="primary" onClick={addConcern}>关注</Button>}
        >
        <div className="userName">{ userInfo.userName }</div>
      </List.Item>
    </List>
    {/* <div className="sloganArea">
      <div className="sloganLabel">
        个性签名
      </div>
      <div className="slogen">
        todo: 没有字段
      </div>
    </div> */}
    { !mySdkStore.isHideSomeFunctions &&
    <List style={{ margin: '12px 0 20px'}}>
      <List.Item extra={ userInfo.goodFriendTag || '未设置' } onClick={handleCollect}>
        标签
      </List.Item>
    </List>
    }
    <div style={{ margin: mySdkStore.isHideSomeFunctions ? '24px 12px 0' : '0 12px' }}>
      <Button block color="primary" style={{ marginBottom: 12 }} onClick={handleCreateConversation}>发消息</Button>
      <Button block onClick={handleRtc}>音视频通话</Button>
    </div>
    <Popup visible={collectionCompProps.visible} destroyOnClose bodyClassName="selectorOperationsBarComponnet-collectionPopup">
      <Collection onClose={() => setCollectCompProps({ visible: false })} {...collectionCompProps} />
    </Popup>
    { rtcPageProps.visible && <Rtc {...rtcPageProps} />}
  </div>)
}